<?php

namespace App\CompanyApi\Controllers;


use App\CompanyApi\Services\Auth\AuthService;
use App\Enums\ResponseCode;
use App\Enums\SmsEnum;
use App\Exceptions\ApiExceptions;
use App\Exceptions\BusinessException;
use App\Http\Controllers\Api\AbstractApiController;
use App\Models\CompanyLoginModel;
use App\Models\CompanyModel;
use App\Services\Sms\SmsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException;
use Mews\Captcha\Captcha;

class AuthController extends AbstractApiController
{
    /**
     * 验证码登录
     * @param Request $request
     * @return JsonResponse
     * @throws ApiExceptions
     * @throws BusinessException
     */
    public function mobileLogin(Request $request): JsonResponse
    {
        $credentials = $request->validate([
            'mobile' => 'required',
            'verify_code' => 'required',
        ], [
            'mobile.required' => '手机号不能为空',
            'verify_code.required' => '验证码不能为空',
        ]);
        //        //验证码验证
        SmsService::verify($credentials['mobile'], $credentials['verify_code'], SmsEnum::LOGIN_CODE);
        $cacheKey = "login-company-api-chat{$credentials['mobile']}";
        $lock = Cache::lock($cacheKey, 60);
        if (!$lock->get()) {
            throw new ApiExceptions('请勿重复提交');
        }
        $userInfo = CompanyLoginModel::query()->where('mobile', $credentials['mobile'])->first();
        if (!$userInfo) {
            //账号不存在注册新用户
            CompanyLoginModel::query()->create([
                'mobile' => $credentials['mobile'],
                'is_lock' => CompanyModel::VERIFY_WAITING,
            ]);
            $userInfo = CompanyLoginModel::query()->where('mobile', $credentials['mobile'])->first();
        }
        $token = auth('company-api')->login($userInfo);
        //获取最后一次的token并加入黑名单
        $lastToken = Cache::get("userCompanyLoginToken:{$userInfo->id}");
        if ($lastToken) {
            try {
//                auth('api')->setToken($lastToken)->invalidate();
            } catch (JWTException $e) {
                //因为让一个过期的token再失效，会抛出异常，所以我们捕捉异常，不需要做任何处理
            }
        }
        $expiresIn = auth('api')->factory()->getTTL() * 60000;
        // 将用户token存入缓存
        Cache::set("userCompanyLoginToken:{$userInfo->id}", $token, $expiresIn);
        $userInfo->last_at = now();
        $userInfo->last_ip = $request->ip();
        $userInfo->save();
        return self::success('登录成功', ResponseCode::OK, [
            'access_token' => $token,
            'token_type' => 'Bearer ',
            'expires_in' => $expiresIn,
            'username' => $userInfo->contact_person_name,
        ]);
    }

    /**
     * 用户登陆方法
     * @param Request $request
     * @param AuthService $service
     * @return JsonResponse
     * @throws ApiExceptions
     */
    public function login(Request $request,AuthService $service): JsonResponse
    {
        $input = $request->validate([
            'mobile' => 'required',
            'password' => 'required',
            'captcha' => 'required|captcha_api:'. request('key') . ',math'
        ], [
            'mobile.required' => '手机号不能为空',
            'password.required' => '密码不能为空',
            'captcha.required' => '验证码不能为空',
            'captcha.captcha_api' => '验证码不正确',
        ]);
        $result = $service->login(
            mobile: $input['mobile'],
            password: $input['password'],
        );
        return self::success(trans("success"), ResponseCode::OK, $result);
    }

    /**
     * 获取验证码
     * @param Request $request
     * @return JsonResponse
     */
    public function mobileVerifyCode(Request $request)
    {
        $input = $request->validate([
            'mobile' => 'required',
        ], [
            'mobile.required' => '手机号不能为空',
        ]);
        try {
            SmsService::send($input['mobile'], 'LOGIN_CODE',$request->getClientIp(),3);
        }catch (BusinessException $exception) {
            return $this->error($exception->getMessage());
        }
        return $this->success(trans("短信发送成功"));
    }
    /**
     * 用户信息
     * @param AuthService $service
     * @return JsonResponse
     */
    public function me(AuthService $service): JsonResponse
    {
        $result = $service->me(auth('company-api')->user());
        return self::success(trans("success"), ResponseCode::OK, $result);
    }
    //退出登录
    public function logout(): JsonResponse
    {
        if (!auth('company-api')->guest()) {
            auth('company-api')->logout();
        }
        return self::success(trans("success"));
    }

    /**
     * 返回验证码
     * @param Captcha $captcha
     * @return JsonResponse
     * @throws \Exception
     */
    public function getCaptchaApi(Captcha $captcha): JsonResponse
    {
        return self::success(trans("success"), ResponseCode::OK, $captcha->create('math', true));
    }
}
